package com.itcast.demo.remoterfc.httpurlconnection;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Objects;

@RestController
@RequestMapping("/rfc")
@Slf4j
public class HttpUrlDoGetOrDoPostController {
    public static String httpUrl = "...?";
    public static final String httpMethod = "GET";
    public static final String basicAppToken = "";
    public static final String params = "";

    @PostMapping("/rfc")
    public void getRemoteRfc(@RequestBody ProductBean productBean) throws Exception {
        if (Objects.nonNull(productBean)) {
            return;
        }
        String pageIndex = productBean.getPageIndex();
        String pageSize = productBean.getPageSize();
        String[] orderId = productBean.getOrder_id();
        StringBuilder sb = new StringBuilder();
        if (Objects.nonNull(pageIndex)) {
            sb.append(URLEncoder.encode("pageIndex", "UTF-8"))
                    .append("=").append(URLEncoder.encode(pageIndex, "UTF-8"));
        }
        if (Objects.nonNull(pageSize)) {
            sb.append("&").append(URLEncoder.encode("pageSize", "UTF-8"))
                    .append("=").append(URLEncoder.encode(pageSize, "UTF-8"));
        }
        if (Objects.nonNull(orderId)) {
            sb.append("&").append(URLEncoder.encode("params", "UTF-8"))
                    .append("=");
            Params params1 = new Params();
            params1.setOrder_id(orderId);

            String jsonString = JSON.toJSONString(params1);
            sb.append(URLEncoder.encode(jsonString, "UTF-8"));
        }
        String params = sb.toString();
        httpUrl += params;
        params = "";

        String jsonResponse = request(httpUrl, basicAppToken, params);
        System.out.println(jsonResponse);
    }

    private String request(String httpUrl, String basicAppToken, String params) {
        URL url = null;
        InputStream in = null;
        HttpURLConnection connection = null;
        BufferedReader responseReader = null;
        StringBuilder sb = new StringBuilder();
        try {
            url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(httpMethod);
            connection.setRequestProperty("Authorization", basicAppToken);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(30000);
            // 隐式打开链接，建立输入流，向指定的url传入参数
//            connection.getOutputStream().write(params.getBytes("UTF-8"));
            connection.getOutputStream().flush();
            connection.getOutputStream().close();
            int responseCode = connection.getResponseCode();
            String responseMessage = connection.getResponseMessage();
            System.out.println("responseCode: " + responseCode + ", responseMessage: " + responseMessage);
            if (HttpURLConnection.HTTP_OK == responseCode) {
                String readLine;
                responseReader = new BufferedReader(new InputStreamReader
                        (connection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("");
                }
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (responseReader != null) {
                try {
                    responseReader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return sb.toString();
    }

}
